
import { _decorator, Component, Node, UITransform, Prefab, assetManager, instantiate, Color, Sprite, Canvas, find, Graphics, color, v2, Pool } from 'cc';
import { Config } from '../Config';
import { Cell } from '../Constructs/Cell';
import { TmpRoom } from '../Constructs/TmpRoom';
import { DemoColors } from '../Enums/DemoColors';
import { CellNode } from '../Prefabs/CellNode';
const { ccclass, property } = _decorator;

/**
 * Predefined variables
 * Name = Renderer
 * DateTime = Thu Sep 02 2021 18:10:08 GMT+0800 (中国标准时间)
 * Author = 幻想马修连恩
 * FileBasename = Renderer.ts
 * FileBasenameNoExtension = Renderer
 * URL = db://assets/Scripts/Renderer.ts
 * ManualUrl = https://docs.cocos.com/creator/3.3/manual/zh/
 *
 */

@ccclass('Renderer')
export class Renderer extends Component {
    @property(Node)
    widgetsParent:Node = null;

    @property(Prefab)
    cellPrefab:Prefab = null;

    @property(Graphics)
    delaunayLineNode:Graphics = null;

    start() {
    }

    // update (deltaTime: number) {
    //     // [4]
    // }

    public initMapArea(mapWidth,mapHeight) {
        const transform:UITransform = this.widgetsParent.getComponent(UITransform);
        transform.width = mapWidth;
        transform.height = mapHeight;
        const sprite:Sprite = this.widgetsParent.getComponent(Sprite);
        sprite.color = DemoColors.TotalBg;
    }

    private _cellNodes:Array<Array<CellNode>>;
    public initMapNodes(cells:Array<Array<Cell>>){
        if(this._cellNodes && this._cellNodes.length !== 0){
            console.warn("cellNodes已经初始化过了");
            return;
        }

        let cellWidth = Config.CellWidth;
        let cellHeight = Config.CellHeight;
        this._cellNodes = [];
        for(let row = 0;row < cells.length;row++){
            let rowCells = cells[row];
            for(let col = 0;col < rowCells.length;col++){
                let newNode = instantiate(this.cellPrefab);
                let cellNode:CellNode = newNode.getComponent(CellNode);
                // cellNode.active(false);
                cellNode.initCellNode(this._getCell(cells,row,col),this.widgetsParent,cellWidth,cellHeight);
                cellNode.setCellColor(DemoColors.CellDefault)
                if(!this._cellNodes[row]) this._cellNodes[row] = [];
                this._cellNodes[row][col] = cellNode;
            }
        }

        return this._cellNodes;
    }

    /**
     * 显示房间的颜色
     * @param oriCells 
     * @param room 
     * @param rooms 
     * @param color 
     */
    public setRoomColor(oriCells:Array<Array<CellNode>>,room:TmpRoom,rooms:Array<TmpRoom>,showAnchor:boolean){
        for(let cell of room.cells){
            let isAnchor:boolean = false;
            if(showAnchor){
                for(let r of rooms){
                    if(r.oriAnchor.row === cell.row && r.oriAnchor.column === cell.column){
                        isAnchor = true;
                        break;
                    }
                }
            }
            
            if(showAnchor&&isAnchor) continue;

            let cellNode:CellNode = this._getCellNode(oriCells,cell.row,cell.column);
            cellNode.setCellColor(room.roomColor);
            // cellNode.active(true);
        }
    }

    public drawLines(points:Array<Array<number>>,lines:Array<Array<number>>,cellNodes:Array<Array<CellNode>>,color:Color){
        for(let i=0;i<lines.length;i++){
            let p1Idx = lines[i][0];
            let p2Idx = lines[i][1];
            let p1 = points[p1Idx];
            let p2 = points[p2Idx];
            //四舍五入取cell
            let p1x = Math.round(p1[0]);
            let p1y = Math.round(p1[1]);
            let p2x = Math.round(p2[0]);
            let p2y = Math.round(p2[1]);
            let n1:CellNode = this._getCellNode(cellNodes,p1y,p1x);
            let n2:CellNode = this._getCellNode(cellNodes,p2y,p2x);
            
            this._drawCellNodeLine(n1,n2,color);
        }
    }

    public clearLines(){
        let grahpics:Graphics = this.delaunayLineNode;
        grahpics.clear();
    }

    private _drawCellNodeLine(node1:CellNode,node2:CellNode,color:Color){
        let grahpics:Graphics = this.delaunayLineNode;
        grahpics.strokeColor = color;
        grahpics.moveTo(node1.getPos().x,node1.getPos().y);
        grahpics.lineTo(node2.getPos().x,node2.getPos().y);
        grahpics.stroke();
    }
    
    public setCellArrayColor(nodes:Array<Array<CellNode>>,cells:Array<Cell>,color:Color){
        for(let cell of cells){
            let node:CellNode = this._getCellNode(nodes,cell.row,cell.column);
            if(!node){
                console.error("找不到CellNode:",cell.row," ",cell.column)
            }
            node.setCellColor(color);
        }
    }

    public setCellArrayArrayColor(nodes:Array<Array<CellNode>>,cells:Array<Array<Cell>>,color:Color){
        for(let row of cells){
            for(let c of row){
                let node:CellNode = this._getCellNode(nodes,c.row,c.column);
                if(!node){
                    console.error("找不到CellNode:",c.row," ",c.column)
                }
                node.setCellColor(color);
            }
        }
    }

    private _getCell(cells:Array<Array<Cell>>,row:number,column:number){
        if(!cells[row]) return null;
        if(!cells[row][column]) return null;
        return cells[row][column];
    }
    
    private _getCellNode(cells:Array<Array<CellNode>>,row:number,column:number){
        if(!cells[row]) return null;
        if(!cells[row][column]) return null;
        return cells[row][column];
    }

    public getRandomColor(){
        let r = Math.round(Math.random()*255);
                let g = Math.round(Math.random()*255);
                let b = Math.round(Math.random()*255);
                return new Color(r,g,b,255);
    }
}

/**
 * [1] Class member could be defined like this.
 * [2] Use `property` decorator if your want the member to be serializable.
 * [3] Your initialization goes here.
 * [4] Your update function goes here.
 *
 * Learn more about scripting: https://docs.cocos.com/creator/3.3/manual/zh/scripting/
 * Learn more about CCClass: https://docs.cocos.com/creator/3.3/manual/zh/scripting/ccclass.html
 * Learn more about life-cycle callbacks: https://docs.cocos.com/creator/3.3/manual/zh/scripting/life-cycle-callbacks.html
 */
